﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace vpGrid.Tests
{
    public static class FrameworkExtensions
    {
        public static bool IsNullOrEmpty<T>(this List<T> input)
        {
            try
            {
                if (input == null)
                {
                    return true;
                }

                if (input.Count == 0)
                {
                    return true;
                }

                return false;
            }
            catch (Exception)
            {
                //TODO : log
                return false;
            }
        }

        public static bool IsNotNullOrEmpty<T>(this List<T> input)
        {
            return input.IsNullOrEmpty() == false;
        }

        public static string ToJson<T>(this T input) where T : class
        {
            try
            {
                if (input == null)
                {
                    return "{}";
                }

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, input);
                    return Encoding.UTF8.GetString(stream.ToArray());
                }

            }
            catch (Exception ex)
            {
                //TODO : log
                string msg = ex.Message;
                return "{}";
            }
        }

        public static string ToJson<T>(this List<T> input) where T : class
        {
            try
            {
                if (input.IsNullOrEmpty())
                {
                    return "[]";
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("[");

                int itemCount = input.Count;
                int i = 1;
                foreach (var item in input)
                {
                    string jsonItem = item.ToJson<T>();
                    sb.Append(jsonItem);
                    if (i < itemCount)
                    {
                        sb.AppendLine(",");
                    }
                    i += 1;
                }

                sb.AppendLine("]");
                return sb.ToString();

            }
            catch (Exception ex)
            {
                //TODO : log
                return "[]";
            }
        }


    }
}
